import './index.scss'

import { formateDate, formatFileSize } from '../../utils'
import { useEffect, useRef, useState } from 'react'
import { Dropdown, Image, message } from 'antd'
import { createUserDropdownStyles, defaultTheme } from '../../static/styles/dropDown'
import { useAppSelector } from '../../utils/storeHook/storeHook'
import ConfirmDialog from '../../components/ConfirmDialog'
import { MyRecorder } from '../index'
import kbAvatar from '../../static/imgs/kbAvatar.png'

interface MessageItemT{
    message_id:string,
    channel_id?:string,
    direct_chat_id?:string,
    content:string,
    sender_id:string,
    created_at:string,
    sender_avatar:string,
    sender_name:string
}

interface AttachmentT {
    file_id: string;
    file_url: string;
    file_name: string;
    width?: number;
    height?: number;
    size: number;
    mime_type: string;
    alt_text?: string;
    duration?: number;
}

interface recorder{
    file_id: string;
    file_url: string;
    file_name: string;
    size: number;
    mime_type: string;
    duration: number;
}

interface messageInpT {
    text: string;
    attachments: AttachmentT[];
    recorder?:recorder
}

interface propsT{
    item:MessageItemT;
    onDelete:Function;
    id:string;
    isMGT:boolean;
}

interface dropDownItem {
    key:string,
    label?:string,
    type?:string,
    disabled?:boolean,
    onClick?:()=>void,
}

const MessageItem=({item,onDelete,id,isMGT}:propsT)=>{
    const imgType = ['image/png','image/jpeg','image/gif','image/jpg','image/webp','image/svg']

    const [recorder,setRecorder] = useState<recorder>()
    const [text,setText] = useState<string>('')
    const [imageList,setImageList] = useState<AttachmentT[]>([])
    const [fileList,setFileList] = useState<AttachmentT[]>([])
    const styles = createUserDropdownStyles(defaultTheme)
    const [isHovered, setIsHovered] = useState<string | null>(null);
    const [messageApi, contextHolder] = message.useMessage();
    const [dropdownVis,setDropdownVis] = useState(false)
    const [delMsgDlgVis,setDelMsgDlgVis] = useState(false)

    const textRef = useRef<HTMLDivElement>(null)

    const user_id = useAppSelector(state=>state.auth.user_id)

    const msgMore:dropDownItem[] = [
        // {
        //     key: '1',
        //     label: '回复',
        //     // onClick:()=>setAddChannelDlgVis(true),
        // },
        {
            key: '2',
            label: '复制文字消息',
            onClick:()=>onCopy(),
        },
        {
            key: '11',
            label: '删除消息',
            type: 'danger',
            onClick:()=>{
                setDelMsgDlgVis(true)
                setDropdownVis(false)
            },
            disabled:item.sender_id !== user_id && !isMGT
        },
    ]

        const getItemStyle = (item:dropDownItem) => {
        const baseStyle = styles.listItem;
        let style = { ...baseStyle };

        // 处理伪类状态
        if (isHovered === item.key) {
            style = { ...style, ...baseStyle.hover };
        }

        // 处理特殊类型
        if (item.type === 'danger') {
            style = { ...style, ...baseStyle.danger };
            if (isHovered === item.key) {
                style = { ...style, ...baseStyle.danger?.hover };
            }
        }

        if (item.disabled) {
            style = { ...style, ...baseStyle.disabled };
        }

        if(item.type === 'divider'){
            style = styles.divider
        }

        return {...style,padding:'4px 12px'};
    };

    function downLoadFile(url:string,filename:string){
        fetch(url)
            .then(response => response.blob())
            .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename || url.split('/').pop() || 'download';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        })
        .catch(error => console.error('下载失败:', error));
    }

    function onCopy(){
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        messageApi.success('复制成功')
        setDropdownVis(false)
    }

    function handleDelete(){
        setDropdownVis(false)
        setDelMsgDlgVis(false)
        onDelete(item.message_id)
    }


    useEffect(()=>{
        if(item.content){
            if(!textRef.current) return
            const content:messageInpT = JSON.parse(item.content)
            
            setRecorder(content.recorder)
            setText(content.text)
            textRef.current.innerHTML = content.text
            const imgs:AttachmentT[] = []
            const files:AttachmentT[] = []
            
            content.attachments.forEach(item=>{
                let isImg = false
                
                for(let key of imgType){
                    if(item.mime_type == key){
                        isImg = true
                    }
                    
                }
                if(isImg){
                    imgs.push(item)
                    return
                }else{
                    files.push(item)
                    return
                }
            })
            setImageList(imgs)
            setFileList(files)
        }
    },[item])
    return (
        <>
            {contextHolder}
            <div className="textChat_message_item" id={'msg' + id}>
                <div className="textChat_message_item_other">
                    <div className="textChat_message_avatar">
                        <img loading='lazy' src={item.sender_avatar || kbAvatar} alt="用户头像" />
                    </div>
                    <div className="textChat_message_content">
                        <div className="textChat_message_content_header">
                            <div className="textChat_message_content_username">{item.sender_name}</div>
                            <div className="textChat_message_content_time">{formateDate(item.created_at)}</div>
                        </div>
                        <div className="textChat_message_contentBox">
                            {recorder?
                            <MyRecorder url={recorder.file_url} duration={recorder.duration}></MyRecorder>
                            :<><div className='textChat_message_content_text' ref={textRef}>
                                {/* {text} */}
                            </div>
                            {imageList.length>0&&
                            <div className='textChat_message_content_imgs'>
                                <Image.PreviewGroup
                                    items={imageList.map(item=>item.file_url)}
                                >
                                {
                                    imageList.map(item=><div className='textChat_message_content_imgs_item' key={item.file_id}>
                                        <Image
                                            src={item.file_url}
                                            height={'100%'}
                                            width={'100%'}
                                            // fallback={errImg}
                                        />
                                    </div>)
                                }
                                </Image.PreviewGroup>
                            </div>
                            }
                            {fileList.length > 0 &&
                            <div className='textChat_message_content_files'>
                                <div className="textChat_message_content_files_header">附件</div>
                                {fileList.map(item=><div 
                                    className='textChat_message_content_files_item' key={item.file_id}>
                                    <div className="file_icon">
                                        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M9 13H15M9 9H15M9 17H13M5 21H19C20.1046 21 21 20.1046 21 19V5C21 3.89543 20.1046 3 19 3H5C3.89543 3 3 3.89543 3 5V19C3 20.1046 3.89543 21 5 21Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"></path>
                                        </svg>
                                    </div>
                                    <div className='file_info'>
                                        <div className='file_info_name'>{item.file_name}</div>
                                        <div className='file_info_meta'>
                                            <div className='file_info_meta_type'>
                                                {item.mime_type}
                                            </div>
                                            <div className='file_info_meta_size'>
                                                {formatFileSize(item.size)}
                                            </div>
                                        </div>
                                    </div>
                                    <div className='file_download' onClick={()=>downLoadFile(item.file_url,item.file_name)}>
                                        <svg viewBox="0 0 24 24" fill="none">
                                            <path d="M12 5V15M12 15L8 11M12 15L16 11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            <path d="M5 19H19" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                                        </svg>
                                    </div>
                                </div>)}
                            </div>
                            }</>}
                        </div>
                        <div className="textChat_message_content_actions">
                            {/* <div className="textChat_message_content_action">回复</div> */}
                            <Dropdown 
                                menu={{}}
                                arrow={{ pointAtCenter: true }}
                                destroyOnHidden={true}
                                open={dropdownVis}
                                popupRender={() => (
                                    <div 
                                        style={styles.list} 
                                        onMouseLeave={()=>setDropdownVis(false)}
                                    >
                                        {msgMore.map(item=>(
                                            !item.disabled&&<div
                                                onClick={item.onClick} style={getItemStyle(item)}
                                                key={item.key}
                                                onMouseEnter={() => !item.disabled && setIsHovered(item.key)}
                                                onMouseLeave={() => setIsHovered(null)}
                                            >{item.label}</div>
                                        ))}
                                    </div>
                                )}
                            >
                                <div
                                    className="textChat_message_content_action"
                                    onClick={()=>setDropdownVis(!dropdownVis)}
                                >
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <circle cx="6" cy="12" r="1.5" fill="currentColor"/>
                                        <circle cx="12" cy="12" r="1.5" fill="currentColor"/>
                                        <circle cx="18" cy="12" r="1.5" fill="currentColor"/>
                                    </svg>
                                </div>
                            </Dropdown>
                        </div>
                    </div>
                </div>
            </div>
            <ConfirmDialog 
                visible={delMsgDlgVis} 
                tipText='此操作将从服务器中永久删除该消息，你确定吗？'
                onClose={()=>setDelMsgDlgVis(false)}
                onConfirm={()=>handleDelete()}
            >
            </ConfirmDialog>
        </>
    )
}

export default MessageItem